package main

import (
	"code.google.com/p/cloud9lib/index"
	"encoding/json"
	"flag"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"
)

func route() {

	verb := flag.Arg(0)
	pattern := flag.Arg(2)
	urlstr := flag.Arg(3)

	var err error

	switch verb {
	case "add" :
		err = index.AddRoute(pattern, urlstr)
	case "rem", "del", "remove", "delete", "rm" :
		err = index.DeleteRoute(pattern)
	default :
		fmt.Println("unkown command")
	}

	if err != nil {
		panic(err)
	}
}

func bucket() {

	bucket := flag.Arg(1)
	urlstr := flag.Arg(2)

	err := index.AddBucket(bucket, urlstr)

	if err != nil {
		panic(err)
	}
}

func mux() {

	urlstr := flag.Arg(1)

	err := index.AddMux(urlstr)

	if err != nil {
		panic(err)
	}
}

func listBuckets() {

	resp, err := http.Get(index.INDEX_URL + "/buckets")

	if err != nil {
		panic(err)
	}

	defer resp.Body.Close()
	printBucket(resp)
}

func listRoutes() {

	resp, err := http.Get(index.INDEX_URL + "/routes")

	if err != nil {
		panic(err)
	}

	defer resp.Body.Close()
	printBucket(resp)
}

func listMuxes() {

	resp, err := http.Get(index.INDEX_URL + "/muxes")

	if err != nil {
		panic(err)
	}

	defer resp.Body.Close()
	printBucket(resp)
}

func list() {

	switch flag.Arg(1) {
	case "muxes":
		listMuxes()
	case "buckets":
		listBuckets()
	case "routes":
		listRoutes()
	default:
		fmt.Println("buckets:")
		listBuckets()
		fmt.Println("\nmuxes:")
		listMuxes()
		fmt.Println("\nroutes:")
		listRoutes()
	}
}

func printBucket(resp *http.Response) {

	text, err := ioutil.ReadAll(resp.Body)

	if err != nil {
		panic(err)
	}

	urls := make(map[string]url.URL)
	err = json.Unmarshal(text, &urls)

	if err != nil {
		panic(err)
	}

	for k, v := range urls {
		fmt.Println(k, "\t-> ", v.String())
	}

	fmt.Println()
}

func main() {

	flag.Parse()

	if flag.Arg(0) == "list" {
		list()
		return
	}

	switch flag.Arg(1) {
	case "mux":
		mux()
	case "bucket":
		bucket()
	case "route":
		route()
	default:
		fmt.Println("usage: \n\tadd mux <url>\n\tadd bucket <bucket> <url>\n\tadd/rm route <pattern> <url>\n\tlist [buckes,muxes,routes]")
	}
}
